package com.pureut.order.qiyeweixin;

import java.math.BigDecimal;

public class NumberToChinese {
    private static final String[] CN_NUMBERS = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
    private static final String[] CN_UNITS = {"", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟"};
    private static final String CN_DOLLAR = "元";
    private static final String CN_INTEGER = "整";
    private static final String CN_NEGATIVE = "负";
    private static final int MAX_LENGTH = 16; // 最大支持16位整数

    public String toChinese(BigDecimal amount) {
        if (amount == null) {
            return "";
        }

        StringBuilder result = new StringBuilder();
        long number = amount.movePointRight(2).longValue(); // 转换为分单位
        boolean negative = false;

        if (number < 0) {
            negative = true;
            number = Math.abs(number);
        }

        // 处理小数部分
        int cent = (int)(number % 100);
        number = number / 100;

        // 处理整数部分
        int unitIndex = 0;
        boolean zero = true;
        boolean needZero = false;

        if (number == 0) {
            result.append(CN_NUMBERS[0]);
        }

        while (number > 0) {
            int digit = (int)(number % 10);
            if (digit == 0) {
                if (!zero && !needZero) {
                    needZero = true;
                }
            } else {
                if (needZero) {
                    result.append(CN_NUMBERS[0]);
                    needZero = false;
                }
                zero = false;
                result.append(CN_UNITS[unitIndex]).append(CN_NUMBERS[digit]);
            }
            unitIndex++;
            number = number / 10;
        }

        if (negative) {
            result.append(CN_NEGATIVE);
        }

        result.reverse().append(CN_DOLLAR);

        // 处理小数部分
        if (cent > 0) {
            int jiao = cent / 10;
            int fen = cent % 10;

            if (jiao > 0) {
                result.append(CN_NUMBERS[jiao]).append("角");
            }
            if (fen > 0) {
                result.append(CN_NUMBERS[fen]).append("分");
            }
        } else {
            result.append(CN_INTEGER);
        }

        return result.toString();
    }
}